package com.nononsenseapps.feeder.ui.feed

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.gitee.wsl.common.ui.ext.applicationViewModels
import com.nononsenseapps.feeder.model.FeedListViewModel
import com.nononsenseapps.feeder.model.GlobalViewModel
import com.nononsenseapps.feeder.ui.R
import com.zchu.labelselection.Label
import com.zchu.labelselection.LabelSelectionFragment
import com.zchu.labelselection.OnEditFinishListener
import kotlinx.coroutines.*
import java.util.ArrayList

abstract class AbstractFeedHotEditFragment: LabelSelectionFragment(), OnEditFinishListener {
    /*private val globalViewModel by lazy { getGlobalViewModel()  }
    private val feedListViewModel by lazy{ getFeedListViewModel() }*/

    private val globalViewModel by applicationViewModels<GlobalViewModel>()
    private val feedListViewModel by activityViewModels<FeedListViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mOnEditFinishListener =this
    }

    override fun onEditFinish(selectedLabels: ArrayList<Label>?, unselectedLabel: ArrayList<Label>?, alwaySelectedLabels: ArrayList<Label>?) {
        if(selectedLabels==null)
            globalViewModel.updateHotFeedList(ArrayList())
        else
            globalViewModel.updateHotFeedList(selectedLabels.map { it.id })
       navigateToFeedFragment()
    }

    abstract fun navigateToFeedFragment()

    @SuppressLint("ResourceAsColor")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadDateForModel()
        val bgColor: Int =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    context?.resources?.getColor(R.color.window_background, null)!!
                } else {
                    @Suppress("DEPRECATION")
                    (context?.resources?.getColor(R.color.window_background)!!)
                }
        view.setBackgroundColor(bgColor)
    }

    private fun loadDateForModel(){
       lifecycleScope.launch(Dispatchers.Default) {
                val saveHotFeedList = globalViewModel.hotFeedList.value
                feedListViewModel.getLiveFeeds().apply {
                    val (hotFeedList, unSelectedFeedList) = this.map { Label(it.id, it.displayTitle) }.partition { feedToCheck: Label -> saveHotFeedList!!.contains(feedToCheck.id) }
                    withContext(Dispatchers.Main) {
                        initData(hotFeedList, unSelectedFeedList, null)
                    }
                }
        }
    }
}